const wsUrl = "ws://18.162.112.52:9001"
const ip = "http://ip.by88.life:8080/"

const aaa = "5" // getRandomNum(1, 10);
const bbb = md5("ZQnpBRGSWyI0CUdu" + aaa + "zT6FNt5/VfjhVfj");
let uuid = getUuid()
FingerprintJS.load().then(res => {
    res && res.get().then(rs => {
        uuid = rs.visitorId
    })
})



const ws = new WebSocket(wsUrl, []);
ws.onopen = e => {
    console.error('---ws open--', e)
    getCode()
}
ws.onclose = e => {
    console.error('---ws onclose--', e)
}
ws.onmessage = event => {
    // console.error('---ws onmessage--', event.data, typeof event.data == "string")
    try {

        if (typeof event.data == "string") {
            let array = [];
            for (let i = 0; i < event.data.length; i++) {
                array.push(event.data.charCodeAt(i));
            }
            let buf = new Uint8Array(array);
            ReceiveMessage(buf);
            return;
        }

        let reader = new FileReader();
        reader.readAsArrayBuffer(event.data);
        reader.onload = function () {
            let buf = new Uint8Array(reader.result);
            ReceiveMessage(buf);
        };
    } catch (e) {
        console.log("异常拉！！！", e);
    }
}
ws.onerror = e => {
    console.error('---ws onerror--', e)
}


let loading = false

// 登录
function login() {
    if (!username.value || !password.value || !code.value) return
    if (loading) return
    loading = true
    setTimeout(() => {
        loading = false
    }, 2000)
    const rq = MessageMap[659]()
    rq.login_type = 1;
    rq.username = username.value;
    rq.password = password.value;
    rq.device_id = uuid;
    rq.device_model = "apple";
    rq.channel_id = 1;
    rq.aaa = aaa;
    rq.bbb = bbb;
    rq.ip = ip;
    rq.captcha = code.value;
    sendMsg(rq)
}
// 注册
function register() {
    if (!username.value || !password.value || !password2.value || !code.value) return
    if (password.value != password2.value) return alert('两次密码不一致')
    if (loading) return
    loading = true
    setTimeout(() => {
        loading = false
    }, 2000)
    const rq = MessageMap[788]()

    rq.register_type = 1
    rq.username = username.value;
    rq.password = password.value;
    rq.sign = getRandomSign(uuid);
    rq.ip_error = "0";
    rq.aaa = aaa;
    rq.bbb = bbb;
    rq.ip = ip;
    rq.captcha = code.value;
    rq.device_id = uuid;
    rq.device_model = "apple";
    rq.channel_id = 1;
    rq.currency = 1; // 默认越南盾
    rq.inviteCode = '';
    rq.name = '';
    rq.phone = '';
    sendMsg(rq)
}
// 获取验证码
function getCode() {
    const rq = MessageMap[794]()
    rq.sign = getRandomSign(uuid);
    // rq.sign = `Mzk3eEdtZWVaZkJaZVprWQ==`
    rq.aaa = aaa;
    rq.bbb = bbb;
    sendMsg(rq)
}


const tab1 = document.querySelector('.tab1')
const tab2 = document.querySelector('.tab2')

const login_tab = document.querySelector('.login_tab')
const register_tab = document.querySelector('.register_tab')

const login_btn = document.querySelector('.login_btn')
const register_btn = document.querySelector('.register_btn')

login_tab.addEventListener('click', () => {
    tab1.style.zIndex = 2
    tab2.style.zIndex = 1
    login_btn.style.zIndex = 5
    register_btn.style.zIndex = 1
    // 
    password2Box.style.opacity = '0'
})
register_tab.addEventListener('click', () => {
    tab1.style.zIndex = 1
    tab2.style.zIndex = 2
    login_btn.style.zIndex = 1
    register_btn.style.zIndex = 5
    //
    password2Box.style.opacity = '1'
})



const username = document.querySelector('#username')
const password = document.querySelector('#password')
const password2 = document.querySelector('#password2')
const password2Box = document.querySelector('#password2Box')
const code = document.querySelector('#code')

const p_open = document.querySelector('#p_open')
const p_close = document.querySelector('#p_close')

const p2_open = document.querySelector('#p2_open')
const p2_close = document.querySelector('#p2_close')

p_open.addEventListener('click', () => {
    p_open.className = 'icon hidden_icon'
    p_close.className = 'icon'
    password.type = 'text'
})
p2_open.addEventListener('click', () => {
    p2_open.className = 'icon hidden_icon'
    p2_close.className = 'icon'
    password2.type = 'text'
})
p_close.addEventListener('click', () => {
    p_open.className = 'icon'
    p_close.className = 'icon hidden_icon'
    password.type = 'password'
})
p2_close.addEventListener('click', () => {
    p2_open.className = 'icon'
    p2_close.className = 'icon hidden_icon'
    password2.type = 'password'
})



var ringBuffer = new RingBuffer();
function ReceiveMessage(buf) {
    var len = buf.byteLength;
    if (buf == undefined || buf == null || len == 0) {
        return;
    }
    for (var i = 0; i < len; ++i) {
        ringBuffer.Push(buf[i]);
    }
    while (true) {
        var receivedlength = ringBuffer.DataLength();
        if (receivedlength < 4) {
            return;
        }

        let bodyLen = ringBuffer.decode_msg_total_length();

        if (bodyLen < 1) {
            return;
        }

        if (receivedlength < bodyLen) {
            return;
        }
        DecodeMessage(bodyLen);
    }
}



function DecodeMessage(bodyLen) {
    ringBuffer.addHead(4); //先去掉4个字节的包长度，再开始解析msg_id
    let msgID = ringBuffer.decode_msg_id();


    console.error("msgID: " + msgID)
    let messageStruct = MessageMap[msgID];
    if (messageStruct == null) {
        //找不到对应的解码结构体时，循环消息ringbuffer的标识也要往后移，跳过这条消息的数据
        ringBuffer.addHead(bodyLen - 2);
        console.log("msgID not register", msgID);
        return;
    }

    let message = ringBuffer.decode_msg_body(messageStruct, bodyLen - 2);
    if (message.code != 1) {
        if (message.message) {
            console.error('异常协议', message.message)
        }
    }

    const res = JSON.parse(JSON.stringify(message))
    console.log(
        `返回协议的id为 ==> ${msgID}
返回的数据为 ==>`, res
    );

    switch (msgID) {
        case 660: // 登录返回
            if (res.code == 1) {
                console.error('---登录成功', res)
                alert('登录成功')
                loginSuccess()
            } else {
                alert(res.message || 'login fail')
                getCode()
            }
            break
        case 789: // 注册返回
            if (res.code == 1) {
                console.error('---注册成功', res)
                loading = false
                alert('注册成功')
                login()
            } else {
                alert(res.message || 'register fail')
                getCode()
            }
            break
        case 795: // 验证码
            if (res.url) {
                document.querySelector('#otp').innerHTML = `<img src="${res.url}" />`
            }
            break
    }
}




function sendMsg(data, needFilterSendRate = false, timeOutCallBack = null, filterCallBack = null) {
    let msg = JSON.parse(JSON.stringify(data))
    delete msg.build
    delete msg.decode
    delete msg.encode
    delete msg.getMsgID
    console.log(`发送的协议为: ==> ${data.getMsgID()}
发送的数据为：==>`, msg);

    //消息包编号，服务器需要用到
    let buf = [];
    let count = calcPacketCount();
    int8ToByte(count, buf);

    //编码消息体
    data.build(buf);

    //编码整个包头，不包括自身的4个字节
    let bodylen = swab32_msg_total_length(buf.length);
    let bodyLenBuf = [];
    encode_msg_total_length(bodylen, bodyLenBuf);

    //把bodylen放到buf最前面
    for (let i = 3; i >= 0; --i) {
        buf.unshift(bodyLenBuf[i]);
    }

    let sendbuffer = new Uint8Array(buf).buffer;

    ws.send(sendbuffer);
}

// s
var packageCount = 1
function calcPacketCount() {
    let count = packageCount++;
    if (packageCount > 255) {
        packageCount = 1;
    }

    return count;
}